/*
 * @Author       : xh
 * @Date         : 2022-11-14 19:53:18
 * @LastEditors: y001554
 * @FileName     :
 */
import { defineComponent, toRefs, computed, watch, ref, unref } from 'vue'
// import IconClose from './components/icon-close'
// import IconOpen from './components/icon-open'
// import IconCheck from './components/icon-check'
// import IconUncheck from './components/icon-uncheck'
// import IconAll from './components/icon-all'
// import IconNone from './components/icon-none'
import {
  ArrowRight,
  ArrowDown,
  Remove,
  CircleCheckFilled,
  CirclePlusFilled,
  CircleClose
} from '@element-plus/icons-vue'
import useToggle from './composables/use-toggle'
import { TreeItem, treeProps, TreeProps } from './types'
import './index.scss'
import { deepMerge } from '../../../utils'
import { PROPS } from './composables/setting'
export default defineComponent({
  name: 'M-Tree',
  props: treeProps,
  emits: ['update:modelValue'],
  setup(props: TreeProps, { slots, emit }) {
    let { data, checkable, modelValue } = toRefs(props)
    let { prop } = props
    prop = deepMerge(PROPS, prop)
    let { labelAfter, color, activeColor } = prop
    const { openedData, toggle, subsDataObj } = useToggle(data.value, prop)

    console.log('slots', activeColor, prop, deepMerge(PROPS, prop))
    const result: any = ref([...modelValue.value])

    // 增加缩进的展位元素
    const Indent = () => {
      return <span class="ylui-indent"></span>
    }

    //@注释
    //@name:折叠图标渲染
    //@params:
    //@des:
    const renderIcon = (item: TreeItem) => {
      return item.children ? (
        <span
          class={[item.disableToggle && 'toggle-disabled', 'ylui-icon']}
          onClick={() => toggle(item)}
        >
          {
            // 增加插槽逻辑
            slots.iconLeft ? (
              slots.iconLeft(item)
            ) : item.open ? (
              <el-icon color={activeColor}>
                <ArrowRight />
              </el-icon>
            ) : (
              <el-icon color={color}>
                <ArrowDown />
              </el-icon>
            )
          }
        </span>
      ) : (
        <Indent />
      )
    }

    //@注释
    //@name:全选图标选中
    //@params:
    //@des:
    const renderChoose = (item: TreeItem, all: Boolean) => {
      item.all = all
      return (
        <span class="ylui-cursor" onClick={() => renderCooseHandle(item, !all)}>
          {slots.iconCenter ? (
            slots.iconCenter(item)
          ) : all ? (
            <el-icon color={activeColor}>
              <CirclePlusFilled />
            </el-icon>
          ) : (
            <el-icon color={color}>
              <Remove />
            </el-icon>
          )}
        </span>
      )
    }
    //@注释
    //@name:全选函数
    //@params:
    //@des:
    const renderCooseHandle = (item: TreeItem, bool: Boolean) => {
      const kname = item[prop.keyName || 'id' || 'value'].toString()
      const subsValue = [...subsDataObj[kname], kname]
      // debugger
      if (kname) {
        if (bool) {
          result.value = [...new Set([...result.value, ...subsValue])]
        } else {
          subsValue.map((it) => {
            const index = result.value.indexOf(it)
            result.value.splice(index, 1)
          })
        }
      }
    }

    //@注释
    //@name:最右边单选选中
    //@params:
    //@des:
    const renderCheck = (item: TreeItem) => {
      const kname = item[prop.keyName || 'id' || 'value'].toString()
      const checked = result.value.includes(kname)
      item.checked = checked
      return (
        <span
          class="ylui-cursor"
          onClick={() => renderCheckHandle(item, !checked)}
        >
          {slots.iconRight ? (
            slots.iconRight(item)
          ) : checked ? (
            // <IconCheck class="mr-xs" color={activeColor} />
            <el-icon color={activeColor}>
              <CircleCheckFilled />
            </el-icon>
          ) : (
            <el-icon color={color}>
              <CircleClose />
            </el-icon>
          )}
        </span>
      )
    }
    //@注释
    //@name:选中函数
    //@params:
    //@des:
    const renderCheckHandle = (item: TreeItem, bool: Boolean) => {
      const kname = item[prop.keyName || 'id' || 'value'].toString()
      // debugger
      if (kname) {
        if (bool) {
          result.value = [...new Set([...result.value, kname])]
        } else {
          const index = result.value.indexOf(kname)
          // debugger
          if (index >= 0) {
            // debugger
            result.value.splice(index, 1)
          }
        }
      }
    }

    //@注释
    //@name:文字渲染 （计算全选个数）
    //@params:
    //@des:
    const renderLabel = (item: TreeItem) => {
      const kname = item[prop.keyName || 'id' || 'value'].toString()

      let sum = subsDataObj[kname]?.length + 1 || 1
      let check = 0

      if (subsDataObj[kname]) {
        for (let i of subsDataObj[kname]) {
          const it = i
          // console.log('it', it)
          if (result.value.includes(it)) {
            check += 1
          }
        }
      }
      if (result.value.includes(kname)) {
        check += 1
      }
      return {
        text: `(${check || 0}/${sum})`,
        all: sum > 0 ? check >= sum : false
      }
    }

    //@注释
    //@name:渲染节点
    //@params:
    //@des:
    const renderNode = (item: TreeItem) => {
      const { key = '', label, disabled = false, open, level } = item
      // const nodeId = handleInitNodeClassNameReflect(disabled, key, label) // 获取nodeId
      const itemTexts = renderLabel(item)
      // console.log('itemTexts,', itemTexts)
      return (
        <div
          class={['ylui-tree-node', open && 'ylui-tree-node--open']}
          style={{ paddingLeft: `${24 * (level - 1)}px` }}
        >
          <div class={['ylui-tree-node__content']}>
            {/* 折叠图标 */}
            {renderIcon(item)}
            {/* 全选框 */}
            <aside class="ylui-tree-node__content-left">
              {checkable.value &&
                item.children &&
                renderChoose(item, itemTexts.all)}
            </aside>
            <article class="ylui-tree-node__content-body">
              {/* 文本 */}
              <div
                class={[
                  'ylui-tree-node__title',
                  item.disabled && 'select-disabled'
                ]}
              >
                {item.label}
              </div>
              <div class="ylui-tree-node__slot">
                {labelAfter
                  ? labelAfter(item)
                  : slots.labelAfter && slots.labelAfter(item)}
              </div>
              <span class={['ylui-tree-node__title']}>{itemTexts.text}</span>
              <div style="flex:1"></div>
            </article>
            <aside class="ylui-tree-node__content-right">
              {checkable.value && renderCheck(item)}
            </aside>
          </div>
        </div>
      )
    }

    watch(
      () => result,
      (v) => {
        // debugger
        emit('update:modelValue', v.value)
      },
      {
        deep: true,
        immediate: false
      }
    )

    watch(
      () => props.modelValue,
      (v) => {
        // debugger
        // alert(JSON.stringify(v) !== JSON.stringify(result.value))
        if (JSON.stringify(v) !== JSON.stringify(result.value)) {
          result.value = [...v]
        }
      },
      {
        deep: true,
        immediate: false
      }
    )
    return () => {
      return (
        <div class="ylui-tree">
          {openedData.value.map((item: TreeItem) => renderNode(item))}
          {!(openedData.value && openedData.value.length > 0) && (
            <span>加载中</span>
          )}
        </div>
      )
    }
  }
})
